#ifdef MULTIMEDIA

#include "nativeaudio.h"
#include "audioformat.h"

#include <QtMultimedia/QAudioDeviceInfo>
#include <QIODevice>
#include <QDebug>

NativeAudio::NativeAudio(const QString name,AudioFormat *format, QObject *parent) :
    QIODevice(parent)
{
    say("init");
    //switching from my AudioFormat to QAudioFormat
    this->format.setSampleRate(format->getSampleRate());
    this->format.setSampleSize(format->getSampleSize());
    this->format.setCodec(format->getCodec());
    this->format.setChannelCount(format->getChannelsCount());
    this->name = name;
    in = 0;
    out = 0;
    devIn = 0;
    devOut = 0;
}
bool NativeAudio::open(OpenMode mode) {
    say("opening");
    QIODevice::open(mode);
    bool state = false;
    if ((mode == QIODevice::WriteOnly) || (mode == QIODevice::ReadWrite)) {
        QAudioDeviceInfo info = QAudioDeviceInfo::defaultOutputDevice();
        out = new QAudioOutput(info,format,this);
        //in case of unsuported format: we return false
        if (!info.isFormatSupported(format)) {
            say("unsuported output format");
            return false;
        }
        out->setObjectName(name);
        devOut = out->start();
        say("ok for write");
        state = true;
    }
    if ((mode == QIODevice::ReadOnly) || (mode == QIODevice::ReadWrite)) {
        QAudioDeviceInfo info = QAudioDeviceInfo::defaultInputDevice();
        if (!info.isFormatSupported(format)) {
            say("unsuported input format");
            return false;
        }
        in = new QAudioInput(info,format,this);
        in->setObjectName(name);
        devIn = in->start();
        say("ok for read");
        if (state) state = true;
    }
    return state;
}
void NativeAudio::close() {
    QIODevice::close();
    say("closed");
}

qint64 NativeAudio::writeData(const char *data, qint64 len) {
    return devOut->write(data,len);
}
qint64 NativeAudio::readData(char *data, qint64 maxlen) {
   return devIn->read(data,maxlen);
}
void NativeAudio::say(const QString message) {
    qDebug() << "Native: " + message;
}
#endif
